import { ref, watch, computed, type ComputedRef } from "vue";
import { defineStore } from "pinia";
import { store } from "../index";
import gradeConfig from "../../../public/gradeConfig.json";

const useSystemStore = defineStore("system", () => {
  // 黑白模式标识
  const isDark = ref(true);
  window.api.getStore("isDark").then((res: boolean) => (isDark.value = !(res === false)));
  const partType = ref(0); // 零件类型
  // 零件相关档次及分档
  const grades: ComputedRef<Array<PartGrade>> = computed(() => gradeConfig[partType.value].items);
  const gradeStandard: ComputedRef<Array<GradeStatistic>> = computed(
    () => gradeConfig[partType.value].standard
  );
  const tableConfigs: ComputedRef<Array<GradeTableConfig>> = computed(
    () => gradeConfig[partType.value].table
  );
  const materialCode = ref(); // 物料编码
  const materialName = ref(); // 物料名称
  const fromLine = ref(); // 物料加工线

  const partTypeOptions = gradeConfig.map((item, index) => ({
    label: item.partName,
    value: index
  }));

  // 监听白天模式和黑夜模式的切换
  watch(
    isDark,
    (val: boolean) => {
      const html = document.querySelector("html");
      if (val) {
        html?.classList.add("dark");
      } else {
        html?.classList.remove("dark");
      }
      window.api.setStore("isDark", val);
    },
    {
      immediate: true
    }
  );

  return {
    isDark,
    partType,
    partTypeOptions,
    grades,
    gradeStandard,
    tableConfigs,
    materialCode,
    materialName,
    fromLine
  };
});

export function useSystemStoreHook() {
  return useSystemStore(store);
}
